const api = require("../../../utils/request.js");
Page({
  data: {
    info: {},
    commentStyle: "",
    communityStyle: "",
    commentCount: 0,
    commentValue: "",
    commentList: [],
    isFocus: false,
    bottomHeight: 0,
    userId: "",
    isReply: "2",
    fullScreen: false,
    replyInfo: {},
    publishId: "",
  },
  async onLoad(e) {
    let bottomPadding = getApp().globalData.bottomPadding;
    wx.showShareMenu({
      withShareTicket: true, // 是否使用带 shareTicket 的转发
      menus: ["shareAppMessage", "shareTimeline"], // 需要显示的分享按钮
    });
    this.setData({
      communityStyle:
        "height: calc(100% - " + (100 + bottomPadding + 6) + "rpx)",
      commentStyle:
        "padding-bottom:" + (bottomPadding + 16) + "rpx;bottom:0px;",
      userId: wx.getStorageSync("loginInfo").userId,
      publishId: e.articleId,
    });
    this.getDetails({ publishId: e.articleId });
    this.getComments({ publishId: e.articleId });
  },
  onShow() {
    wx.updateShareMenu({
      withShareTicket: true,
    });
  },
  onShareAppMessage(res) {
    return {
      title: `${this.data.info.nickName}发表的文章`,
      path: `/pages/community/detail/index?articleId=${this.data.info.id}`,
    };
  },
  playVideo() {
    let videoContext = wx.createVideoContext("myvideo", this);
    videoContext.requestFullScreen();
    this.setData({
      fullScreen: true,
    });
  },
  closeVideo() {
    //执行退出全屏方法
    let videoContext = wx.createVideoContext("myvideo", this);
    videoContext.exitFullScreen();
  },
  fullScreen(e) {
    //视屏进入、退出全屏
    let isFull = e.detail.fullScreen;
    //视屏全屏时显示加载video，非全屏时，不显示加载video
    this.setData({
      fullScreen: isFull,
    });
  },
  async profileClick(e) {
    // 判断是点击自己的图像 还是点击别人的图像
    let userId = wx.getStorageSync("loginInfo").userId;
    let url =
      e.currentTarget.dataset.item.userId === userId
        ? "/pages/home/index"
        : "/pages/home/otherProfile/index";
    wx[
      e.currentTarget.dataset.item.userId === userId
        ? "switchTab"
        : "navigateTo"
    ]({
      url: `${url}?userId=${e.currentTarget.dataset.item.userId}&nickName=${e.currentTarget.dataset.item.nickName}`,
    });
  },
  async subscribeClick(e) {
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo.avatarUrl && userInfo.nickName && userInfo.phoneNumber) {
      let data = {
        followUserId: e.currentTarget.dataset.info.userId,
      };
      let url =
        e.currentTarget.dataset.info.displayFollow === "2"
          ? "/wxUser/cancelFollow"
          : "/wxUser/addFollow";
      await api.request({
        url,
        data,
        method: "post",
      });
      this.getDetails({ publishId: this.data.publishId });
    } else {
      getApp().globalData.jump = true;
      wx.switchTab({
        url: `/pages/user/index`,
      });
    }
  },

  async getDetails(data) {
    let res = await api.request({
      url: "/publish/getPublishInfo",
      data,
      method: "get",
    });
    res.data.publishContent = JSON.parse(res.data.publishContent);
    delete res.data.publishId;
    this.setData({ info: res.data });
  },
  async getComments(data) {
    let res = await api.request({
      url: "/comment/listComment",
      data,
      method: "get",
    });
    let info = { ...this.data.info, commentCount: res.rows.length };
    this.setData({ commentList: res.rows, info });
  },
  async deleteComment(e) {
    let res = await api.request({
      url: "/comment/deleteComment",
      data: { commentId: e.currentTarget.dataset.item.id },
      method: "get",
    });
    this.setData({ commentList: res.rows });
    wx.showToast({ title: "删除评论成功", duration: 2000 });
    this.getComments({ publishId: this.data.publishId });
  },
  replyClick(e) {
    this.setData({
      replyInfo: e.currentTarget.dataset.item,
      isReply: "1",
      isFocus: true,
    });
  },
  commentFocus(e) {
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo.avatarUrl && userInfo.nickName && userInfo.phoneNumber) {
      let bottomPadding = wx.getStorageSync("bottomPadding");
      this.setData({
        commentStyle: "padding-bottom:" + (bottomPadding + 16) + "rpx;bottom:" + e.detail.height + "px;",
        isFocus: true,
      }); //将键盘的高度设置为comment容器与page容器下边界之间的距离。
    } else {
      getApp().globalData.jump = true;
      wx.switchTab({
        url: `/pages/user/index`,
      });
    }
  },
  commentInput(e) {
    this.setData({ commentValue: e.detail.value }); // 输入内容
  },
  commentBlur(e) {
    let bottomPadding = wx.getStorageSync("bottomPadding");
    this.setData({
      commentStyle:
        "padding-bottom:" + (bottomPadding + 16) + "rpx;bottom: 0px;",
      isFocus: false,
    }); // 失去焦点
  },
  async commentCommit() {
    let { commentValue, info, replyInfo, isReply } = this.data;
    let data = {
      publishId: info.id,
      isReply,
      commentContent: commentValue,
      replyCommentId: replyInfo.id,
      replyUserId: replyInfo.userId,
    };
    await api.request({ url: "/comment/addComment", data, method: "post" });
    this.setData({ commentValue: "", replyInfo: {}, isReply: "2" });
    wx.showToast({
      title: "评论发送成功",
      icon: "success",
      duration: 2000,
    });
    this.getComments({ publishId: this.data.publishId });
  },
  previewImage(e) {
    let list = e.currentTarget.dataset.src;
    wx.previewImage({
      current: list[0], // 当前显示图片的链接/路径
      urls: list[1], // 需要预览的图片链接/路径列表
    });
  },
  oneImageLoad(e) {
    let factor1 = (getApp().globalData.screenWidth - 68) / 344;
    let factor2 = e.detail.width / e.detail.height;
    let mode = factor2 > factor1 ? "widthFix" : "heightFix";
    let info = this.data.info;
    let publishContent = [];
    info.publishContent.forEach((item) => {
      if (item.type.indexOf("img") !== -1) {
        let idx = item.content.findIndex(
          (val) => val === e.currentTarget.dataset.src[0]
        );
        if (idx !== -1) {
          item.mode = mode;
        }
      }
      publishContent.push(item);
    });
    info.publishContent = publishContent;
    this.setData({ info });
  },
  openLocation(e) {
    wx.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.map.latitude || 0),
      longitude: parseFloat(e.currentTarget.dataset.map.longitude || 0),
      name: e.currentTarget.dataset.map.detailAddress, //位置名
      address: e.currentTarget.dataset.map.addressDes, //地址的详细说明
    });
  },
  async likeClick() {
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo.avatarUrl && userInfo.nickName && userInfo.phoneNumber) {
      let url =
        this.data.info.isAwarded === "1"
          ? "/publish/cancelAward"
          : "/publish/addAward";
      await api.request({
        url,
        data: { awardPublishId: this.data.info.id },
        method: "post",
      });
      let info = {
        ...this.data.info,
        isAwarded: this.data.info.isAwarded === "1" ? "2" : "1",
      };
      this.setData({ info });
    } else {
      getApp().globalData.jump = true;
      wx.switchTab({
        url: `/pages/user/index`,
      });
    }
  },
});
